<?php

namespace App\Http\Controllers\Mini;

use App\Models\Ads;
use App\Models\Areas;
use App\Models\Cases;
use App\Models\Categorys;
use App\Models\Collections;
use App\Models\Footprints;
use App\Models\Services;
use App\Models\StoreEvaluates;
use App\Models\Stores;
use App\Models\UserInfos;
use App\Models\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Pagination\LengthAwarePaginator;

class StoreController extends Controller
{
    /**
     * 供应商分类
     * @route api.store.storeCate
     */
    public function storeCate(Request $request){
        try{
            $lists = Categorys::getCascaderList();
            $fields = ['id','store_name','logo','call','view','praise','service_scope','hot','quality'];
            foreach ($lists as $k=>$v){//获取分类下的商铺
                $lists[$k]['store'] = Stores::allLists(['recommend'=>2],$fields, null, 4);
                foreach ($lists[$k]['store'] as $kk=>$vv){
                    $lists[$k]['store'][$kk]['view'] = strlen($vv['view'])>=4 ? '999+' : $vv['view'];
                    $lists[$k]['store'][$kk]['call'] = strlen($vv['call'])>=4 ? '999+' : $vv['call'];
                }
                //获取分类下的广告
                $params = [
                    'cate_id' => $v['value'],
                    'adsense_id' => 34,
                    'status' => 1,
                    'limit' => 1,
//                    'start_at' => date('Y-m-d H:i:s'),
//                    'end_at' => date('Y-m-d H:i:s'),
                ];
                $lists[$k]['adv'] = Ads::getList($params, ['id','adsense_id','thumb','link']);
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商筛选
     * @route api.store.storeScreen
     */
    public function storeScreen(Request $request){
        try{
            $lists = [];
            $lists['cate'] = Categorys::getCascaderList();
            $lists['area'] = Areas::get(['id','name']);//服务区域

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商列表
     * @route api.store.storeLists
     * @param cid_id 二级分类id
     * @param area 区域id
     * @param page 页码
     * @param limit 条数
     * @param sid 排序 1成交量 2浏览量 3好评量
     */
    public function storeLists(Request $request){
        try{
            $map = [
                'cid_id' => $request->post('cid_id'),//二级分类id
                'area' => (int)$request->post('area'),//区域id
            ];
            $page = (int)$request->post('page',1);//页码
            $limit = (int)$request->post('limit',5);//条数
            $sid = (int)$request->post('sid');//排序 1成交量 2浏览量 3好评量
            if ($sid == 1){
                $sort = 'service';
            }elseif ($sid == 2){
                $sort = 'view';
            }elseif ($sid == 3){
                $sort = 'praise';
            }else{
                $sort = 'created_at';
            }
            $fields = ['id','user_id','store_name','logo','call','view','service','service_scope','hot','quality'];
            $lists = Stores::webLists($map, $fields, $page, $limit, $sort, 'desc');
            foreach ($lists as $key=>$val){
                $lists[$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                $lists[$key]['call'] = strlen($val['call'])>=4 ? '999+' : $val['call'];
                $lists[$key]['service'] = strlen($val['service'])>=4 ? '999+' : $val['service'];
                $lists[$key]['master_name'] = UserInfos::where('user_id',$val['user_id'])->value('master_name');
                $lists[$key]['master_phone'] = UserInfos::where('user_id',$val['user_id'])->value('master_phone');
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商详情-基本信息
     * @route api.store.storeDetails
     * @param user_id 用户id
     * @param store_id 供应商id
     * @return is_collect 0:未收藏 1:已收藏
     */
    public function storeDetails(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            $user_info = Users::where('id',$user_id)->where('status','<>',-1)->first();

            $store_id = (int)$request->post('store_id');//供应商id
            $seller_id = Stores::where('id',$store_id)->value('user_id');//当前店铺主人id
            if (empty($store_id) || empty($seller_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            if (!empty($user_info) && $user_info['id'] == $seller_id) return response()->json(["code"=>0, "msg"=>'您已是该店铺供应商']);

            $fields = ['id','user_id','store_name','logo','hot','quality','area_info','workingtime','call','praise','cate_id','description'];
            $lists = Stores::details(['id'=>$store_id], $fields);
            $lists['master_name'] = UserInfos::where('user_id',$lists['user_id'])->value('master_name');//联系人姓名
            $lists['master_phone'] = UserInfos::where('user_id',$lists['user_id'])->value('master_phone');//联系人电话
            $lists['call'] = strlen($lists['call'])>=4 ? '999+' : $lists['call'];
            $lists['praise'] = strlen($lists['praise'])>=4 ? '999+' : $lists['praise'];
            //二级分类
            $lists['cate_id'] = explode(',',$lists['cate_id']);
            foreach ($lists['cate_id'] as $k => $v){
                $pidTree[] =Categorys::where('id',$v)->first('name');
            }
            $lists['cate_id'] = $pidTree;
            //判断是否收藏
            $lists['is_collect'] = 0;//默认未收藏
            if (!empty($user_info)){
                if ($user_info['type'] == 1){
                    $collect = Collections::where(['collect_id'=>$store_id,'user_id'=>$user_info['id'],'type'=>4])->value('collect_id');
                    $lists['is_collect'] = empty($collect) ? 0 : 1;
                }
                //添加足迹
                $foot_arr = [
                    'user_id' => $user_info['id'],
                    'foot_id' => $store_id,
                    'type'    => 1,
                ];
                Footprints::create($foot_arr);
            }
            Stores::where('id',$store_id)->increment('view');//浏览量加1

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商图片
     * @route api.store.storeImg
     * @param store_id 供应商id
     * @param page 页码
     * @param limit 条数
     * @return bool
     */
    public function storeImg(Request $request){
        try{
            $store_id = (int)$request->post('store_id');//供应商id
            $page = (int)$request->post('page',1);//页码
            $limit = (int)$request->post('limit',4);//条数
            if (empty($store_id) || empty($page) || empty($limit)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $lists = Stores::details(['id'=>$store_id],'image');

            //计算每页分页的初始位置
            $offset = ($page * $limit) - $limit;
            //实例化LengthAwarePaginator类，并传入对应的参数
            if(!empty($lists['image'])){
                $res = new LengthAwarePaginator(
                    array_slice($lists['image'], $offset, $limit, false),
                    count($lists['image']),
                    $limit, $page,
                    ['path' => $request->url(), 'query' => $request->query()]
                );
            }else{
                $res = new LengthAwarePaginator(
                    array_slice([], $offset, $limit, false),
                    count([]),
                    $limit, $page,
                    ['path' => $request->url(), 'query' => $request->query()]
                );
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $res
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商合作伙伴
     * @route api.store.storePartners
     * @param store_id 供应商id
     * @param page 页码
     * @param limit 条数
     * @return bool
     */
    public function storePartners(Request $request){
        try{
            $store_id = (int)$request->post('store_id');//供应商id
            $page = (int)$request->post('page',1);//页码
            $limit = (int)$request->post('limit',4);//条数
            if (empty($store_id) || empty($page) || empty($limit)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $lists = Stores::details(['id'=>$store_id],'partners');

            //计算每页分页的初始位置
            $offset = ($page * $limit) - $limit;
            //实例化LengthAwarePaginator类，并传入对应的参数
            if(!empty($lists['partners'])){
                $res = new LengthAwarePaginator(
                    array_slice($lists['partners'], $offset, $limit, false),
                    count($lists['partners']),
                    $limit, $page,
                    ['path' => $request->url(), 'query' => $request->query()]
                );
            }else{
                $res = new LengthAwarePaginator(
                    array_slice([], $offset, $limit, false),
                    count([]),
                    $limit, $page,
                    ['path' => $request->url(), 'query' => $request->query()]
                );
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $res
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商服务
     * @route api.store.storeService
     * @param store_id 供应商id
     * @param page 页码
     * @param limit 条数
     */
    public function storeService(Request $request){
        try{
            $store_id = (int)$request->post('store_id');//供应商id
            $page = (int)$request->post('page',1);//页码
            $limit = (int)$request->post('limit',4);//条数
            if (empty($store_id) || empty($page) || empty($limit)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $lists = Services::allLists(['store_id'=>$store_id],['id','store_id','thumb','title'], $page, $limit);

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商服务详情
     * @route api.store.storeServiceDetails
     * @param cases_id 服务id
     */
    public function storeServiceDetails(Request $request){
        try{
            $service_id = (int)$request->post('service_id');//服务id
            if (empty($service_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $lists = Services::details(['id'=>$service_id]);

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商案例
     * @route api.store.storeCases
     * @param store_id 供应商id
     * @param page 页码
     * @param limit 条数
     */
    public function storeCases(Request $request){
        try{
            $store_id = (int)$request->post('store_id');//供应商id
            $page = (int)$request->post('page',1);//页码
            $limit = (int)$request->post('limit',4);//条数
            if (empty($store_id) || empty($page) || empty($limit)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $lists = Cases::allLists(['store_id'=>$store_id], ['id','store_id','thumb','title'], $page, $limit);

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商案例详情
     * @route api.store.storeCasesDetails
     * @param cases_id 案例id
     * @return bool
     */
    public function storeCasesDetails(Request $request){
        try{
            $cases_id = (int)$request->post('cases_id');//案例id
            if (empty($cases_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $lists = Cases::details(['id'=>$cases_id]);

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商评价
     * @route api.store.storeEvaluateLists
     * @param store_id 供应商id
     * @param page 页码
     * @param limit 条数
     */
    public function storeEvaluateLists(Request $request){
        try{
            $store_id = (int)$request->post('store_id');//供应商id
            $page = (int)$request->post('page',1);//页码
            $limit = (int)$request->post('limit',4);//条数
            if (empty($store_id) || empty($page) || empty($limit)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $map = [
                'store_id' => $store_id,
                'evaluates_type' => (int)$request->post('evaluates_type',1),//1:好评 2：中评 3：差评
            ];
            $lists = StoreEvaluates::allLists($map,['user_name','user_avatar','content','average_star','type','created_at'],$page,$limit);
            foreach ($lists as $k=>$v){
                $lists[$k]['user_name'] = '**'.mb_substr($v['user_name'],-2,4,"utf-8");
            }
            $sum = StoreEvaluates::counts(['store_id'=>$store_id]);//总评论数
            $good = StoreEvaluates::counts(['store_id'=>$store_id,'type'=>1]);//好评数
            $speed = StoreEvaluates::sums(['store_id'=>$store_id], 'speed');
            $quality = StoreEvaluates::sums(['store_id'=>$store_id], 'quality');
            $attitude = StoreEvaluates::sums(['store_id'=>$store_id], 'attitude');
            $store['sum'] = $sum;//评价总数
            $store['avg_good'] = empty($sum) ? 0 : intval(round (($good/$sum)*100));//好评率
            $store['avg_speed'] = empty($sum) ? 0 : intval(round ($speed/$sum));//平均工作速度
            $store['avg_quality'] = empty($sum) ? 0 : intval(round ($quality/$sum));//平均工作质量
            $store['avg_attitude'] = empty($sum) ? 0 : intval(round ($attitude/$sum));//平均工作态度
            $store['good'] = $good;//好评数
            $store['middle'] = StoreEvaluates::counts(['store_id'=>$store_id,'type'=>2]);//中评数
            $store['bad'] = StoreEvaluates::counts(['store_id'=>$store_id,'type'=>3]);//差评数
            $evaluate['list'] = $lists;
            $evaluate['store'] = $store;

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $evaluate
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商收藏
     * @route api.store.storeCollect
     * @param user_id 用户id
     * @param collect_id 收藏内容id
     */
    public function storeCollects(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $collect_id = (int)$request->post('collect_id');
            if (empty($collect_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $userinfo = Users::where(['id'=>$user_id, 'status'=>1])->value('type');
            if (empty($userinfo)) return response()->json(["code"=>0, "msg"=>'用户不存在']);
            if ($userinfo != 1) return response()->json(["code"=>0, "msg"=>'供应商不能收藏']);
            $collect = Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>4])->value('id');
            if (empty($collect)){
                $params = [
                    'collect_id' => $collect_id,
                    'user_id' => $user_id,
                    'collect_at' => date('Y-m-d H:i:s'),
                    'type' => 4,
                ];
                Collections::create($params);
                Stores::where('id',$collect_id)->increment('collections');
                return response()->json(["code"=>1, "msg"=>'收藏成功']);
            }else {
                Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>4])->delete();
                return response()->json(["code"=>1, "msg"=>'取消收藏成功']);
            }
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 供应商评价
     * @route api.store.storeEvaluates
     * @param user_id 用户id
     * @param store_id 店铺id
     * @param content 评价内容
     * @param speed 速度
     * @param quality 质量
     * @param attitude 态度
     */
    public function storeEvaluates(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $userinfo = Users::where(['id'=>$user_id, 'status'=>1])->first(['username','avatar','type']);
            if (empty($userinfo)) return response()->json(["code"=>0, "msg"=>'用户不存在']);
            if($userinfo['type'] != 1) return response()->json(["code"=>0, "msg"=>'供应商不能评价供应商']);
            //TODO 拨打了供应商的电话才可以评价。。。流程等电话信息下来后才写
            $params = [
                'user_id' => $user_id,
                'user_name' => $userinfo['username'],
                'user_avatar' => $userinfo['avatar'],
                'store_id' => (int)$request->post('store_id'),
                'content' => (string)$request->post('content'),
                'speed' => (int)$request->post('speed'),
                'quality' => (int)$request->post('quality'),
                'attitude' => (int)$request->post('attitude'),
            ];
            $params['store_name'] = Stores::where('id',$params['store_id'])->value('store_name');
            $params['average_star'] = intval(round(($params['speed']+$params['quality']+$params['attitude'])/3));//平均分
            if($params['average_star'] ==5 || $params['average_star'] == 4){
                $params['type'] = 1;//好评
            }elseif ($params['average_star'] ==3){
                $params['type'] = 2;//中评
            }elseif ($params['average_star'] ==2 || $params['average_star'] == 1){
                $params['type'] = 3;//差评
            }
            StoreEvaluates::create($params);
            Stores::where('id',$params['store_id'])->increment('praise');//评论量加1
            //计算好评率
            $all = StoreEvaluates::where(['store_id'=>$params['store_id']])->where('status','<>',-1)->count();
            $goods = StoreEvaluates::where(['store_id'=>$params['store_id'], 'type'=>1])->where('status','<>',-1)->count();
            $credit = $goods/$all*100;
            Stores::where('id',$params['store_id'])->update(['credit'=>$credit]);

            return response()->json(["code"=>1, "msg"=>'评价成功']);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

}